<?php

/**
 * @param unknown $mobile
 * @param unknown $data
 * @param number $tmplID
 * @return multitype:number string
 */
function send_mobile_sms($mobile,$data=array(),$tmplID=1){
	if (!_checkmobile($mobile)) return array('status' => 0,'msg' => '手机号码格式不正确');
	if (empty($data)) return array('status' => 0,'msg' => '短信内容不合法');
	$sms = new sms();
	$result = $sms->sendTemplateSMS($mobile, $data, $tmplID);
	if (is_array($result)){
		return array('status' => 0,'msg' => $result['msg']);
	}elseif ($result==true){
		return array('status' => 1,'msg' => '发送成功');
	}
	return array('status' => 0,'msg' => '发送失败');
}

function _htmtocode2($content) {
	$content = str_replace('%',' ',$content);
	$content = str_replace("<", " ", $content);
	$content = str_replace(">", " ", $content);
	$content = str_replace("\n", " ", $content);
	$content = str_replace(" ", " ", $content);
	$content = str_replace('"', " ", $content);
	$content = str_replace("'", " ", $content);
	$content = str_replace("$", " ", $content);
	$content = str_replace('}',' ',$content);
	$content = str_replace("&nbsp;", " ", $content);
	$content = str_replace("<br/>", " ", $content);
	return $content;
}

/**
 *	发送用户手机验证码
 *	mobile @用户手机号
 *   uid    @用户的ID
 */
function send_mobile_set_code($mobile=null,$uid=null,$_type=1){
	if(!$uid){
		return array('status' => 0,'msg' => "发送用户手机认证码,用户ID不能为空！");
	}

	if(!$mobile){
		return array('status' => 0,'msg' => "发送用户手机认证码,手机号码不能为空!");
	}

	$mobilecodes = mt_rand(100000,999999);//验证码
	/*
	if ($_type == 1){
		$template = M('caches')->where(array('key' => 'template_mobile_set'))->getField('value');
		if (empty($template)){
			$content = '你在'.getConfig('web_name')."的短信验证码是:：{$mobilecodes}，请您注意查收！【".getConfig('web_name')."】";
		}else{
			$content = str_replace('000000', $mobilecodes, $template);
		}
	}elseif ($_type == 2){
		$template = M('caches')->where(array('key' => 'template_mobile_apply'))->getField('value');
		if (empty($template)){
			$content = '你在'.getConfig('web_name')."的短信验证码是:：{$mobilecodes}，请您注意查收！【".getConfig('web_name')."】";
		}else{
			$content = str_replace('000000', $mobilecodes, $template);
		}
	}
	*/
	
	if ($_type==1){
		$tplId = SET_PWD_TPL;
	}elseif ($_type==2){
		$tplId = APPLYFOR_AGENT_TPL;
	}
	$result = send_mobile_sms($mobile,array($mobilecodes),$tplId);
	if ($result['status']==1){
		$data = array(
				'uid' => $uid,
				'mobile' => $mobile,
				'code' => $mobilecodes,
				'type' => $_type,
				'status' => 0,
				'active_time' => 3600,	//一个小时内
				'time' => NOW_TIME
		);
		M('sms_activity_code')->data($data)->add();
		return array('status' => 1,'msg' => '验证码发送成功','data' => $data);
	}else{
		return array('status' => 0,'msg' => '验证码发送失败');
	}

	/**
	 * 	$sends = new sms();
	//返回0发送成功
	if ($sends->sendSms($content,$mobile) == 0){
		$data = array(
				'uid' => $uid,
				'mobile' => $mobile,
				'code' => $mobilecodes,
				'type' => $_type,
				'status' => 0,
				'active_time' => 3600,	//一个小时内
				'time' => NOW_TIME
		);
		M('sms_activity_code')->data($data)->add();
		return array('status' => 1,'msg' => '验证码发送成功','data' => $data);
	}else{
		return array('status' => 0,'msg' => '验证码发送失败');
	}
	 */
}

/**
 *	发送用户手机认证码短信
 *	mobile @用户手机号
 *   uid    @用户的ID
 */

function send_mobile_reg_code($mobile=null,$uid=null){
	if(!$uid){
		echo json_encode(array("status" => 0,"msg" => '发送用户手机认证码,用户ID不能为空！'));
		exit;
	}
	if(!$mobile) {
		echo json_encode(array('status' => 0,'msg' => '发送用户手机认证码,手机号码不能为空!'));
		exit;
	}
	
	$checkcodes= rand(100000,999999).'|'.time();//验证码
	aud("UPDATE `@#_member` SET mobilecode='$checkcodes' where `uid`='$uid'");
	$checkcodes = explode("|",$checkcodes);
	
	/*
	$template = query("select * from `@#_caches` where `key` = 'template_mobile_reg'");
	if(!$template){
		$content =  "您在".getConfig('web_name')."的短信验证码是:".strtolower($checkcodes[0]).'【'.getConfig('web_name').'】';
	}
	if(empty($template['value'])){
		$content =  "您在".getConfig('web_name')."的短信验证码是:".strtolower($checkcodes[0]).'【'.getConfig('web_name').'】';
	}else{
		if(strpos($template['value'],"000000") == true){
			$content= str_ireplace("000000",strtolower($checkcodes[0]),$template['value']);
		}else{
			$content = $template['value'].strtolower($checkcodes[0]);
		}
	}
	//测试
	//恭喜您！您云购的商品已成功！幸运码是：100006866 请24小时内联系客服提交收货地址！【吉祥夺宝】
	//return _sendmobile($mobile,$content);
	//$content =  "你在组团云购的短信验证码是:989913【吉祥夺宝】";
	return _renhu_sendmobile($mobile, $content);
	*/
	
	$result = send_mobile_sms($mobile,array($checkcodes[0]),REGISTER_TPL);
	return $result;
	
}


/**
 *	发送用户手机获奖短信
 *	mobile @用户手机号
 *   uid    @用户的ID
 *	code   @中奖码
 */

function send_mobile_shop_code($mobile=null,$uid=null,$code=null){
	if(!$uid){
		echo json_encode(array('status' => 0,'msg' => '发送用户手机获奖短信,用户ID不能为空！'));
		exit;
	}
	if(!$mobile){
		echo json_encode(array('status' => 0,'msg' => '发送用户手机获奖短信,手机号码不能为空!'));
		exit;
	}
	if(!$code){
		echo json_encode(array('status' => 0,'msg' => '发送用户手机获奖短信,中奖码不能为空!'));
		exit;
	}
	/*
	$template = M('caches')->where(array('key' => 'template_mobile_shop'))->find();
	if(!$template){
		$template = array();
		$content =  "你在".getConfig('web_name')."购买的商品已中奖,中奖码是:".$code.'【'.getConfig('web_name').'】';
	}
	if(empty($template['value'])){
		$content =  "你在".getConfig('web_name')."购买的商品已中奖,中奖码是:".$code.'【'.getConfig('web_name').'】';
	}else{
		if(strpos($template['value'],"00000000") == true){
			$content= str_ireplace("00000000",$code,$template['value']);
		}else{
			$content = $template['value'].$code;
		}
	}
	return _renhu_sendmobile($mobile,$content);
	*/
	$result = send_mobile_sms($mobile,array($code),LOTTERY_NOTICE_TPL);
	return $result;
}

/*
 新建一期商品
info 	 商品的ID 或者 商品的数组
使用此函数注意传进来的的商品期数不等于最大期数
autocommit @是否开启事物
*/
function content_add_shop_install($info=null,$autocommit=true){
	$model = new CoreModel();
	if($autocommit){
		$model->startTrans();
	}

	unset($info['id']);
	unset($info['q_uid']);
	unset($info['q_user']);
	unset($info['q_user_code']);
	unset($info['q_content']);
	unset($info['q_counttime']);
	unset($info['q_end_time']);
	unset($info['opentime']);
	unset($info['opencode']);

	$info['xsjx_time']=0;
	$info['time'] = time();
	$info['qishu'] = intval($info['qishu']);
	$info['qishu']++;
	$info['canyurenshu'] = '0';
	$info['shenyurenshu'] = $info['zongrenshu'];
	$info['codes_table'] = content_get_codes_table();
	$info['q_showtime']= 'N';
	$info['title'] = _htmtocode($info['title']);
	$info['title2'] = _htmtocode($info['title2']);
	
	$keys  = $vals = '(';
	foreach($info as $key=>$val){
		$keys.="`$key`,";
		$vals.="'$val',";
	}
	$keys = rtrim($keys,',');
	$vals = rtrim($vals,',');
	$keys.= ')';
	$vals.= ')';

	$sql = "INSERT INTO `@#_shoplist` ".$keys." VALUES ".$vals;
	$q1 = aud($sql);
	$id = $model->getLastInsID();
	$q2 = content_get_go_codes($info['zongrenshu'],3000,$id);
	if($autocommit){
		if($q1 && $q2){
			$model->commit();
			return true;
		}else{
			$model->rollback();
			return false;
		}
	}else{
		if($q1 && $q2){
			return true;
		}else{
			return false;
		}
	}

}

/*
 生成夺宝码
CountNum @ 生成个数
len 	    @ 生成长度
sid	    @ 商品ID
*/
function content_get_go_codes($CountNum=null,$len=null,$sid=null){
	$table = query("SELECT * from `@#_caches` where `key` = 'shopcodes_table' LIMIT 1");
	$table = '@#_shopcodes_'.$table['value'];

	$num = ceil($CountNum/$len);
	$code_i = $CountNum;

	//$CountNum 小于3000时执行
	if($num == 1){
		$codes=array();
		for($i=1;$i<=$CountNum;$i++){
			$codes[$i]=10000000+$i;
		}
		shuffle($codes);
		$codes = serialize($codes);
		$query = aud("INSERT INTO `$table` (`s_id`, `s_cid`, `s_len`, `s_codes`,`s_codes_tmp`) VALUES ('$sid', '1','$CountNum','$codes','$codes')");
		unset($codes);
		return $query;
	}

	$query_1 = true;
	// $num = 2; 100
	for($k=1;$k<$num;$k++){
		$codes=array();
		for($i=1;$i<=$len;$i++){
			$codes[$i] = 10000000+$code_i;
			$code_i--;
		}
		shuffle($codes);
		$codes=serialize($codes);
		$query_1 = aud("INSERT INTO `$table` (`s_id`, `s_cid`, `s_len`, `s_codes`,`s_codes_tmp`) VALUES ('$sid', '$k','$len','$codes','$codes')");
		unset($codes);
	}

	$CountNum = $CountNum -(($num-1)*$len);
	$codes=array();

	for($i=1;$i<=$CountNum;$i++){
		$codes[$i]=10000000+$code_i;
		$code_i--;
	}
	shuffle($codes);
	$codes=serialize($codes);
	$query_2 = aud("INSERT INTO `$table` (`s_id`, `s_cid`,`s_len`, `s_codes`,`s_codes_tmp`) VALUES ('$sid', '$num','$CountNum','$codes','$codes')");
	unset($codes);
	return $query_1 && $query_2;
}
//content_get_go_codes(ceil($zongrenshu/3000),3000,$shopid);

/*
 计算夺宝码表
*/
function content_get_codes_table(){
	$num = query("SELECT * from `@#_caches` where `key` = 'shopcodes_table' LIMIT 1");
	$table = 'shopcodes_'.$num['value'];
	$shopcodes_table = query("SHOW TABLE STATUS LIKE '@#_$table'");

	if(!$shopcodes_table || !$num) return false;
	if($shopcodes_table['Auto_increment'] >= 99999){
		$num = intval($num['value'])+1;
		$shopcodes_table = 'shopcodes_'.$num;
		$q1 = aud("CREATE TABLE `@#_$shopcodes_table` (
				`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
				`s_id` int(10) unsigned NOT NULL,
				`s_cid` smallint(5) unsigned NOT NULL,
				`s_len` smallint(5) DEFAULT NULL,
				`s_codes` text,
				`s_codes_tmp` text,
				PRIMARY KEY (`id`),
				KEY `s_id` (`s_id`),
				KEY `s_cid` (`s_cid`),
				KEY `s_len` (`s_len`)
		) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
				");
				$q2 = aud("UPDATE `@#_caches` SET `value` = '$num' where `key` = 'shopcodes_table'");
		if(!$q1 || !$q2)return false;
	}else{
		$num = intval($num['value']);
		$shopcodes_table = 'shopcodes_'.$num;
	}
	return $shopcodes_table;
}


/* $n 字符串长度,返回一个数组*/
function _getcode($n=10){
	$num=intval($n) ? intval($n) : 10;
	if($num>44)
		$codestr=base64_encode(md5(time()).md5(time()));
	else
		$codestr=base64_encode(md5(time()));
	$temp=array();
	$temp['code']=substr($codestr,0,$num);
	$temp['time']=time();
	return $temp;
}

/**
 *	发送用户验证邮箱
 *	email  @用户邮箱地址
 *   uid    @用户的ID
 */

function send_email_reg($email=null,$uid=null){
	$checkcode = _getcode(10);
	$checkcode_sql = $checkcode['code'].'|'.$checkcode['time'];
	$check_code  = serialize(array("email"=>$email,"code"=>$checkcode['code'],"time"=>$checkcode['time']));
	$check_code_url  = _encrypt($check_code,"ENCODE",'',3600*24);

	$clickurl=WEB_PATH.'/member/user/emailok/'.$check_code_url;
	aud("UPDATE `@#_member` SET `emailcode`='$checkcode_sql' where `uid`='$uid'");
		
	$web_name = getConfig("web_name");
	$title = getConfig("web_name")."激活注册邮箱";
	$template = query("select * from `@#_caches` where `key` = 'template_email_reg'");
	$url = '<a href="';
	$url.= $clickurl.'">';
	$url.= $clickurl."</a>";
	$template['value'] = str_ireplace("{地址}",$url,$template['value']);
	return _sendemail($email,'',$title,$template['value']);
}


/**
 *	发送电子邮件
 *	@email 也可以是一个二维数组，包含邮件和用户名信息
 **/
function _sendemail($email,$username=null,$title='',$content='',$yes='',$no=''){
	$config = include_once ROOT_PATH.'/core/config/email.inc.php';
	if(!$username)$username="";
	if(!$yes)$yes="发送成功,如果没有收到，请到垃圾箱查看,\n请把".$config['fromName']."设置为信任,方便以后接收邮件";
	if(!$no)$no="发送失败，请重新点击发送";
	if(!_checkemail($email)){return false;}
	email::config($config);
	if(is_array($email)){
		email::adduser($email);
	}else{
		email::adduser($email,$username);
	}
	$if=email::send($title,$content);
	if($if){
		return $yes;
	}else{
		return $no;
	}
}

/**
 *	发送用户获奖邮箱
 *	email  		@用户邮箱地址
 *   uid    		@用户的ID
 *	usernname	@用户名称
 *	code  		@中奖号码
 *   shoptitle	@商品名称
 */

function send_email_code($email=null,$username=null,$uid=null,$code=null,$shoptitle=null){
	$template = query("select * from `@#_caches` where `key` = 'template_email_shop'");
	if(!$template){
		$template = array();
		$template['value'] =  "恭喜：{$username},你在". getConfig("web_name")."参与的{$shoptitle}已揭晓,揭晓结果是:".$code;
	}else{
		$template['value'] = str_ireplace("{用户名}",$username,$template['value']);
		$template['value'] = str_ireplace("{商品名称}",$shoptitle,$template['value']);
		$template['value'] = str_ireplace("{中奖码}",$code,$template['value']);
	}
	$title = "恭喜您!!! ";
	return _sendemail($email,'',$title,$template['value']);
}


function userid($uid,$zhi='username'){
	$member = M('member')->where(array('uid' => $uid))->find();
	if($zhi=='username'){
		if($member['username']!=null){
			return _strcut($member['username'],8,"");
		}else if($member['mobile']!=null){
			return _strcut($member['mobile'],7,"");
		}else{
			return _strcut($member['email'],7,"");
		}
	}else{
		return $member[$zhi];
	}
}

//判断商品是否揭晓
function team_get_shop_if_jiexiao($shopid=null){
	$record=query("select * from `@#_teamgoods` where `id`='$shopid' LIMIT 1");
	if(!$record) return false;
	if($record['q_user']){
		$record['q_user'] = unserialize($record['q_user']);
		return $record;
	}else{
		return $record;
	}
}

/*
 * 获取用户昵称
* uid 用户id，或者 用户数组
* type 获取的类型, username,email,mobile
* key  获取完整用户名, sub 截取,all 完整
*/
function get_user_name($uid='',$type='username',$key='sub'){
	if(is_array($uid)){
		if(isset($uid['username']) && !empty($uid['username'])){
			return $uid['username'];
		}
		if(isset($uid['email']) && !empty($uid['email'])){
			if($key=='sub'){
				$email = explode('@',$uid['email']);
				return $uid['email'] = substr($uid['email'],0,2).'*'.$email[1];
			}else{
				return $uid['email'];
			}
		}
		if(isset($uid['mobile']) && !empty($uid['mobile'])){
			if($key=='sub'){
				return $uid['mobile'] = substr($uid['mobile'],0,3).'****'.substr($uid['mobile'],7,4);
			}else{
				return $uid['mobile'];
			}
		}
		return '';
	}else{
		$uid = intval($uid);
		$info = M('Member')->where(array('uid' => $uid))->find();
		if(isset($info[$type]) && !empty($info[$type])){
			return $info[$type];
		}
		if(isset($info['username']) && !empty($info['username'])){
			return $info['username'];
		}
		if(isset($info['email']) && !empty($info['email'])){
			if($key=='sub'){
				$email = explode('@',$info['email']);
				return $info['email'] = substr($info['email'],0,2).'*'.$email[1];
			}else{
				return $info['email'];
			}
		}
		if(isset($info['mobile']) && !empty($info['mobile'])){
			if($key=='sub'){
				return $info['mobile'] = substr($info['mobile'],0,3).'****'.substr($info['mobile'],7,4);
			}else{
				return $info['mobile'];
			}
		}
		return '';
	}
}

function percent($p,$t){
	if($p<=0){return false;}
	return sprintf('%.2f%%',$p/$t*100);
}

/*
 * 获取用户信息
*/
function get_user_key($uid='',$type='img',$size=''){
	if(empty($uid) && $type == 'img'){
		return 'photo/member.jpg';
	}
	if(is_array($uid)){
		if(isset($uid[$type])){
			if($type=='img'){
				$fk = explode('.',$uid[$type]);
				$h = array_pop($fk);
				if($size){
					return $uid[$type].'_'.$size.'.'.$h;
				}else{
					return $uid[$type];
				}
			}
			return $uid[$type];
		}
		return 'null';
	}else{
		$db = M('member');
		$uid = intval($uid);
		$info = $db->query("select {$type} from `".C('DB_PREFIX')."member` where `uid` = '$uid' limit 1");
		$info  = current($info);
		if($type=='img'){
			$fk = explode('.',$info[$type]);
			$h = array_pop($fk);
			if($size){
				return $info[$type].'_'.$size.'.'.$h;
			}else{
				return $info[$type];
			}
		}
		if(isset($info[$type])){
			return $info[$type];
		}
		return 'null';
	}
}


/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function _strcut($string, $length,$dot = '...') {
	$string = trim($string);
	if($length && strlen($string) > $length) {
		//截断字符
		$wordscut = '';
		if(strtolower(G_CHARSET) == 'utf-8') {
			//utf8编码
			$n = 0;
			$tn = 0;
			$noc = 0;
			while ($n < strlen($string)) {
				$t = ord($string[$n]);
				if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$tn = 1;
					$n++;
					$noc++;
				} elseif(194 <= $t && $t <= 223) {
					$tn = 2;
					$n += 2;
					$noc += 2;
				} elseif(224 <= $t && $t < 239) {
					$tn = 3;
					$n += 3;
					$noc += 2;
				} elseif(240 <= $t && $t <= 247) {
					$tn = 4;
					$n += 4;
					$noc += 2;
				} elseif(248 <= $t && $t <= 251) {
					$tn = 5;
					$n += 5;
					$noc += 2;
				} elseif($t == 252 || $t == 253) {
					$tn = 6;
					$n += 6;
					$noc += 2;
				} else {
					$n++;
				}
				if ($noc >= $length) {
					break;
				}
			}
			if ($noc > $length) {
				$n -= $tn;
			}
			$wordscut = substr($string, 0, $n);
		} else {
			for($i = 0; $i < $length - 1; $i++) {
				if(ord($string[$i]) > 127) {
					$wordscut .= $string[$i].$string[$i + 1];
					$i++;
				} else {
					$wordscut .= $string[$i];
				}
			}
		}
		$string = $wordscut.$dot;
	}
	return trim($string);
}


function hueisd_id($sd_id,$leixin=null){
	$sdhf = M('shaidan_hueifu')->where(array('sdhf_id' => $sd_id))->find();
	if(!!$leixin="content"){
		return $sdhf['sdhf_content'];
	}else{
		return $sdhf['sdhf_userid'];
	}
}
function shopimg($shopid){
	$shop = M('shoplist')->where(array('id' => $shopid))->find();
	return $shop['thumb'];
}
function shoplisext($id,$zd='title'){
	$shop = M('shoplist')->where(array('id' => $id))->find();
	return $shop[$zd];
}
function huodemem($shopuserid){
	$userid = M('member')->where(array('uid' => $shopuserid))->find();
	if($userid['username']){
		return $userid['username'];
	}else if($userid['mobile']){
		return _strcut($userid['mobile'],7);
	}else{
		return _strcut($userid['email'],7);
	}
}

function get_ip($id,$ipmac=null){
	$record= M('member_go_record')->where(array('id' => $id))->find();
	$ip=explode(',',$record['ip']);
	if($ipmac=='ipmac'){
		return $ip[1];
	}elseif($ipmac=='ipcity'){
		return $ip[0];
	}
}

//判断商品是否揭晓
function get_shop_if_jiexiao($shopid=null){
	$record = M('shoplist')->where(array('id' => $shopid))->find();
	if(!$record) return false;
	if($record['q_user']){
		$record['q_user'] = unserialize($record['q_user']);
		$record['q_user'] = get_user_name($record['q_user']);
		return $record;
	}else{
		$record['q_user'] = get_user_name($record['q_user']);
		return $record;
	}
}

/**
 * 获取用户名或手提电话号码
 */
function get_user_or_mobile($uid = null){
	if (!$uid) return;
	$userinfo = M('Member')->where(array('uid' => intval($uid)))->find();
	if (!$userinfo) return;
	if($userinfo['username']){
		return $userinfo['username'];
	}elseif (!empty($userinfo['mobile'])){
		return hidtel($userinfo['mobile']);
	}elseif (!empty($userinfo['email'])){
		$str = mb_substr($userinfo['email'],2, 3,'utf-8');
		return str_replace($str, '***', $userinfo['email']);
	}
}

/**
 * 处理电话号变*号
 */
function hidtel($phone){
	$IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话
	if($IsWhat == 1){
		return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone);
	}else{
		return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
	}
}

function yunma($ma,$html="span"){
	$list=explode(",",$ma);
	$st="";
	foreach($list as $list2){
		$st.="<".$html.">".$list2."</".$html.">";
	}
	return $st;
}

function microt($time,$x=null){
	if (empty($time)) return;
	$len=strlen($time);
	if($len<13){
		$time=$time."0";
	}
	$list=explode(".",$time);
	if($x=="L"){
		return date("His",$list[0]).substr($list[1],0,3);
	}else if($x=="Y"){
		return date("Y-m-d",$list[0]);
	}else if($x=="H"){
		return date("H:i:s",$list[0]).".".substr($list[1],0,3);
	}else if($x=="r"){
		return date("Y年m月d日 H:i",$list[0]);
	}else{
		$e = substr($list[1],0,3);
		if (empty($e)){
			$e = '000';
		}
		return date("Y-m-d H:i:s",$list[0]).".".$e;
	}
}


/**
 * 获取网站config信息
 * @param String $key
 * @param String
 */
function getConfig($key){
	if (empty($key)) return;
	$key = addslashes($key);
	$config = M('Config')->where(array('name' => $key))->getField('value');
	return $config;
}

/**
 * 获取消息模板
 * @param String $key
 * @param String
 */
function getMessageTpl($key){
	if (empty($key)) return;
	$key = addslashes($key);
	$data = M('Caches')->where(array('key' => $key))->getField('value');
	return $data;
}

/**
 * 人汇信息，发送短信方法
 */
function _renhu_sendmobile($mobile,$content){
	if(!$mobile){
		return array('status' => 0,'msg' => "测试手机号码不能为空！");
	}

	if(!$content){
		return array('status' => 0,'msg' => "测试短信内容不能为空！");
	}

	
	$config = include ROOT_PATH.'/core/config/mobile.inc.php';
	$account = $config['cfg_mobile_0'];
	if (empty($config) || empty($account)){
		return array('status' => 0,'msg' => "短信功能未开启");
	}

	$sends = new sms($account['mid'],$account['mpass']);
	
	//返回0发送成功
	if ($sends->sendSms($content,$mobile) == 0){
		return array('status' => 1,'msg' => '验证码发送成功');
	}else{
		return array('status' => 0,'msg' => '验证码发送失败');
	}
}


/*字符串转数组*/
function String2Array($String){
	if(NULL==$String)return false;
	$Return=array();
	$String=urldecode($String);
	$TempArray=explode('||',$String);
	$NullValue=urlencode(base64_encode("^^^"));
	foreach ($TempArray as $TempValue) {
		list($Key,$Value)=explode('|',$TempValue);
		$DecodedKey=base64_decode(urldecode($Key));
		if($Value!=$NullValue) {
			$ReturnValue=base64_decode(urldecode($Value));
			if(substr($ReturnValue,0,8)=='^^array^')
				$ReturnValue=String2Array(substr($ReturnValue,8));
			$Return[$DecodedKey]=$ReturnValue;
		}
		else
			$Return[$DecodedKey]=NULL;
	}
	return $Return;
}

/*字符过滤url*/
function safe_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);
	return $string;
}

function p($array){
	echo '<pre>';
	print_r($array);
	echo '</pre>';
}

/*过滤搜索关键词*/
function search_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','',$string);
	$string = str_replace('>','',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);
	$string = str_replace('\\\\','',$string);
	$string = str_replace('/','',$string);
	$string = str_replace('//','',$string);
	return $string;
}

/*获取页面完整url*/
function get_web_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
	$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}

/*获取网站当前地址*/
function get_home_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$path=explode('/',safe_replace($_SERVER['SCRIPT_NAME']));
	if(count($path)==3){
		return $sys_protocal.$_SERVER['HTTP_HOST'].'/'.$path[1];
	}
	if(count($path)==2){
		return $sys_protocal.$_SERVER['HTTP_HOST'];
	}
}


/*HTML安全过滤*/
function _htmtocode($content) {
	$content = str_replace('%','%&lrm;',$content);
	$content = str_replace("<", "&lt;", $content);
	$content = str_replace(">", "&gt;", $content);
	$content = str_replace("\n", "<br/>", $content);
	$content = str_replace(" ", "&nbsp;", $content);
	$content = str_replace('"', "&quot;", $content);
	$content = str_replace("'", "&#039;", $content);
	$content = str_replace("$", "&#36;", $content);
	$content = str_replace('}','&rlm;}',$content);
	return $content;
}

/*手机号码验证*/
function _checkmobile($mobilephone=''){
	if(strlen($mobilephone)!=11){
		return false;
	}
	if(preg_match("/^13[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|14[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$/",$mobilephone)){
		return true;
	}else{
		return false;
	}
}

/*邮箱验证*/
function _checkemail($email=''){
	if(mb_strlen($email)<5){
		return false;
	}
	$res="/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/";
	if(preg_match($res,$email)){
		return true;
	}else{
		return false;
	}
}

/*加密解密 ENCODE 加密   DECODE 解密*/
function _encrypt($string, $operation = 'ENCODE', $key = '', $expiry = 0){
	if($operation == 'DECODE') {
		$string =  str_replace('_', '/', $string);
	}
	$key_length = 4;
	if(defined("G_BANBEN_NUMBER")){
		$enmd5key = include_once ROOT_PATH.'/core/config/code.inc.php';
		$key = md5($key != '' ? $key : $enmd5key['code']);
	}else{
		$key = md5($key != '' ? $key : M_SITE_URL);
	}
	$fixedkey = md5($key);
	$egiskeys = md5(substr($fixedkey, 16, 16));
	$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
	$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
	$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));

	$i = 0; $result = '';
	$string_length = strlen($string);
	for ($i = 0; $i < $string_length; $i++){
		$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
	}
	if($operation == 'ENCODE') {
		$retstrs =  str_replace('=', '', base64_encode($result));
		$retstrs =  str_replace('/', '_', $retstrs);
		return $runtokey.$retstrs;
	} else {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	}
}

function idjia($id){
	return $id+1000000000;
}

function _getcookie($name){
	if(empty($name)){return false;}
	if(isset($_COOKIE[$name])){
		return $_COOKIE[$name];
	}else{
		return false;
	}
}

function _setcookie($name,$value,$time=0,$path='/',$domain=''){
	if(empty($name)){return false;}
	$_COOKIE[$name]=$value;				//及时生效
	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	if(!$time){
		return setcookie($name,$value,0,$path,$domain,$s);
	}else{
		return setcookie($name,$value,time()+$time,$path,$domain,$s);
	}
}

/**
 * 判断邮箱是否存在
 */
function checkEmail($email){
	$data = M('Member')->where(array('email' => $email))->find();
	if($data){
		return false;
	}else{
		return true;
	}
}
/**
 * 判断手机号是否存在
 */
function checkMobile($mobile){
	$data = M('Member')->where(array('mobile' => $mobile))->find();
	if($data){
		return false;
	}else{
		return true;
	}
}